package com.lipaluma.example.clients.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.lipaluma.example.clients.dao.IAccountDAO;
import com.lipaluma.example.clients.dao.IInvoiceDAO;
import com.lipaluma.example.clients.dao.IOrderDAO;
import com.lipaluma.example.clients.model.Account;
import com.lipaluma.example.clients.model.Invoice;
import com.lipaluma.example.clients.model.Order;
import com.lipaluma.example.clients.model.Order.StatusEnum;

@Service
@Transactional
public class InvoiceService {

	private static final double TVA = 0.196;

	@Autowired
	private IInvoiceDAO invoiceDAO;

	@Autowired
	private IOrderDAO orderDAO;

	@Autowired
	private IAccountDAO accountDAO;

	public List<Invoice> generateInvoices() {
		List<Invoice> invoicesGenerated = new ArrayList<Invoice>();
		List<Account> accounts = accountDAO.getAll();
		for (Account account : accounts) {
			List<Order> orders = orderDAO.getLastOrdersCreatedForAccount(account.getId());
			if(!CollectionUtils.isEmpty(orders)) {
				Invoice invoice = createInvoice(orders);
				List<Invoice> invoices = account.getInvoices();
				if(invoices == null)
					account.setInvoices(Arrays.asList(invoice));
				else 
					invoices.add(invoice);
				invoicesGenerated.add(invoice);
				accountDAO.update(account);
			}
		}
		return invoicesGenerated;
	}

	private Invoice createInvoice(List<Order> orders) {
		Invoice invoice = new Invoice();
		invoice.setOrders(orders);
		double amountHT = 0.0;
		for (Order order : orders) {
			order.setStatus(StatusEnum.INVOICED);
			amountHT += order.getTotalAmount();
		}
		invoice.setAmountHT(amountHT);
		invoice.setAmountTTC(amountHT + amountHT*TVA);
		invoice.setCreationDate(new Date());
		invoice.setEcheanceDate(DateTime.now().plusMonths(2).withDayOfMonth(1).minusDays(1).withMillisOfDay(0).toDate());
		return invoice;
	}
	
	public Invoice createInvoice(Long idAccount, List<Order> orders) {
		Invoice invoice = createInvoice(orders);
		invoice.setAccount(accountDAO.getById(idAccount));
		invoiceDAO.persist(invoice);
		return invoice;
	}
}
